import {PopupButton, Text, TouchableOpacity} from 'M/UI/Libraries';
import {logout, userService} from 'WE/Services';
import React, {useEffect, useState} from 'react';
import {Theme} from '@react-navigation/native';
import Style from 'M/UI/Style';

const HomeHeaderRight: React.FC<any> = props => {
  const [name, setName] = useState<string>(userService.getSyncName());
  const [theme, setTheme] = useState<Theme>(Style.theme);
  const onPress = () => {
    props.navigation.navigate('PhoneLogin');
  };
  useEffect(() => {
    userService.getName().then(name => setName(name));
    Style.addThemeChangeListener(setTheme);
    userService.addListener(({name}: {name: string}) => {
      setName(name);
    });
  }, [name]);
  if (name) {
    return (
      <PopupButton
        label={name}
        component={
          <TouchableOpacity
            onPress={() => logout().finally(() => console.log('logout.'))}>
            <Text style={{fontSize: 18}}>退出账号</Text>
          </TouchableOpacity>
        }
      />
    );
  } else {
    return (
      <TouchableOpacity
        style={{
          paddingLeft: 5,
          paddingRight: 5,
          alignItems: 'center',
          justifyContent: 'center',
        }}
        onPress={onPress}>
        <Text style={[{fontSize: 18, color: theme.colors.text}]}>登陆</Text>
      </TouchableOpacity>
    );
  }
};

export default HomeHeaderRight;
